package com.fau.om.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fau.om.entity.MedicalAdmin;
import com.fau.om.entity.MedicalGroup;
import com.fau.om.entity.MedicalOrders;
import com.fau.om.entity.MedicalPlatform;
import com.fau.om.service.IAllocationManagerService;
import com.fau.om.util.Page;
import com.fau.om.util.ParamUtil;
import com.fau.om.util.SystemConfig;

@Service
@Transactional(readOnly = true)
public class AllocationManagerService extends BaseService implements
		IAllocationManagerService {

	@Override
	public Page findAllocationByPage(Map<String, Object> map, MedicalOrders orders, MedicalAdmin admin) {
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrders a where 1=1 and a.hospitalId=? and a.status=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalOrders a where 1=1 and a.hospitalId=? and a.status=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		objectList.add(admin.getEnterpriseId());
		objectList.add(SystemConfig.ORDERS_WAIT_AUDIT_TYPE);
		
		if(SystemConfig.ORDERS_LIST_UNALLOCATE.equals(orders.getListType())) {
			countSql.append("and a.allocateGrade=? ");
			statusSql.append("and a.allocateGrade=? ");
		}else {
			countSql.append("and a.allocateGrade <> ? ");
			statusSql.append("and a.allocateGrade <> ? ");
		}
		objectList.add(SystemConfig.ORDERS_GRADE_INIT);
		
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			countSql.append(" and a.serialNum = ? ");
			statusSql.append(" and a.serialNum = ? ");
			objectList.add(orders.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(orders.getName())) {
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			countSql.append(" and a.name like ? ");
			statusSql.append(" and a.name like ? ");
			objectList.add("%"+name+"%");
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
			map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalOrders> list = new ArrayList<MedicalOrders>();
		if(SystemConfig.ORDERS_LIST_UNALLOCATE.equals(orders.getListType())) {
			for(Object obj : page.getResult()) {
				MedicalOrders bean = (MedicalOrders) obj;
				bean.setTotalMoney(bean.getPayment().add(bean.getFreight()));
				bean.setMediaId(bean.getMedia().getId());
				list.add(bean);
			}
		} else {
			for(Object obj : page.getResult()) {
				MedicalOrders bean = (MedicalOrders) obj;
				if(SystemConfig.ORDERS_GRADE_USER.equals(bean.getAllocateGrade())) {
					MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, bean.getCheckUserId());
					bean.setCheckUserName(checkUser.getName());
					if(!SystemConfig.SUPER_ADMIN.equals(checkUser.getIsSuper())) {
						bean.setGroupName(checkUser.getGroup().getName());
						bean.setCenterName(checkUser.getGroup().getPlatform().getName());
					}
				} else if(SystemConfig.ORDERS_GRADE_GROUP.equals(bean.getAllocateGrade())) {
					MedicalGroup group = (MedicalGroup) this.iBaseDao.getObject(MedicalGroup.class, bean.getGroupId());
					bean.setCenterName(group.getPlatform().getName());
					bean.setGroupName(group.getName());
				} else {
					MedicalPlatform center = (MedicalPlatform) this.iBaseDao.getObject(MedicalPlatform.class, bean.getCenterId());
					bean.setCenterName(center.getName());
				}
				bean.setTotalMoney(bean.getPayment().add(bean.getFreight()));
				bean.setMediaId(bean.getMedia().getId());
				list.add(bean);
			}
		}
		page.setResult(list);
		return page;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void recover(String ordersIds) {
		String ordersId[] = ordersIds.split(",");
		for(String oId : ordersId) {
			MedicalOrders orders = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, oId);
			orders.setCenterId("");
			orders.setGroupId("");
			orders.setCheckUserId("");
			orders.setAllocateGrade(SystemConfig.ORDERS_GRADE_INIT);
		}
	}

	@Override
	public boolean validRecover(String ordersIds) {
		String ordersId[] = ordersIds.split(",");
		boolean flag = true;
		for(String oId : ordersId) {
			MedicalOrders orders = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, oId);
			if(null == orders) {
				flag = false;
				break;
			}
		}
		return flag;
	}

	@Override
	public Page findCenterAllocationByPage(Map<String, Object> map,
			MedicalOrders orders, MedicalAdmin admin) {

		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrders a where 1=1 ");
		StringBuilder statusSql = new StringBuilder("from MedicalOrders a where 1=1 ");
		
		List<Object> objectList = new ArrayList<Object>();
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			countSql.append("and a.centerId=? ");
			statusSql.append("and a.centerId=? ");
			objectList.add(admin.getGroup().getPlatform().getId());
		}
		if(SystemConfig.ORDERS_LIST_UNALLOCATE.equals(orders.getListType())) {
			statusSql.append("and a.allocateGrade=? ");
			countSql.append("and a.allocateGrade=? ");
			objectList.add(SystemConfig.ORDERS_GRADE_CENTER);
		}else {
			statusSql.append("and (a.allocateGrade=? or a.allocateGrade=?) ");
			countSql.append("and (a.allocateGrade=? or a.allocateGrade=?) ");
			objectList.add(SystemConfig.ORDERS_GRADE_GROUP);
			objectList.add(SystemConfig.ORDERS_GRADE_USER);
		}
		
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			countSql.append(" and a.serialNum = ? ");
			statusSql.append(" and a.serialNum = ? ");
			objectList.add(orders.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(orders.getName())) {
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			countSql.append(" and a.name like ? ");
			statusSql.append(" and a.name like ? ");
			objectList.add("%"+name+"%");
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalOrders> list = new ArrayList<MedicalOrders>();
		if(SystemConfig.ORDERS_LIST_UNALLOCATE.equals(orders.getListType())) {
			for(Object obj : page.getResult()) {
				MedicalOrders bean = (MedicalOrders) obj;
				bean.setTotalMoney(bean.getPayment().add(bean.getFreight()));
				bean.setMediaId(bean.getMedia().getId());
				list.add(bean);
			}
		} else {
			for(Object obj : page.getResult()) {
				MedicalOrders bean = (MedicalOrders) obj;
				if(SystemConfig.ORDERS_GRADE_USER.equals(bean.getAllocateGrade())) {
					MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, bean.getCheckUserId());
					if(!SystemConfig.SUPER_ADMIN.equals(checkUser.getIsSuper())) {
						bean.setCheckUserName(checkUser.getName());
						bean.setGroupName(checkUser.getGroup().getName());
					}
				} else {
					MedicalGroup group = (MedicalGroup) this.iBaseDao.getObject(MedicalGroup.class, bean.getGroupId());
					bean.setGroupName(group.getName());
				}
				bean.setTotalMoney(bean.getPayment().add(bean.getFreight()));
				bean.setMediaId(bean.getMedia().getId());
				list.add(bean);
			}
		}
		page.setResult(list);
		return page;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void centerRecover(String ordersIds) {
		String ordersId[] = ordersIds.split(",");
		for(String oId : ordersId) {
			MedicalOrders orders = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, oId);
			orders.setGroupId("");
			orders.setCheckUserId("");
			orders.setAllocateGrade(SystemConfig.ORDERS_GRADE_CENTER);
		}
	}

	@Override
	public Page findGroupAllocationByPage(Map<String, Object> map,
			MedicalOrders orders, MedicalAdmin admin) {
		StringBuilder countSql = new StringBuilder("select count(*) from MedicalOrders a where 1=1 and a.allocateGrade=? ");
		StringBuilder statusSql = new StringBuilder("from MedicalOrders a where 1=1 and a.allocateGrade=? ");
		
		List<Object> objectList = new ArrayList<Object>();
		if(SystemConfig.ORDERS_LIST_UNALLOCATE.equals(orders.getListType())) {
			objectList.add(SystemConfig.ORDERS_GRADE_GROUP);
		}else {
			objectList.add(SystemConfig.ORDERS_GRADE_USER);
		}
		
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			countSql.append("and a.groupId=? ");
			statusSql.append("and a.groupId=? ");
			objectList.add(admin.getGroup().getId());
		}
		
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			countSql.append(" and a.serialNum = ? ");
			statusSql.append(" and a.serialNum = ? ");
			objectList.add(orders.getSerialNum());
		}
		
		if(StringUtils.isNotBlank(orders.getName())) {
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			countSql.append(" and a.name like ? ");
			statusSql.append(" and a.name like ? ");
			objectList.add("%"+name+"%");
		}
		
		//排序
		String[] sortField = (String[]) map.get("sortField");
		String[] sortOrder = (String[]) map.get("sortOrder");
		if(StringUtils .isNotBlank(sortField[0]) && StringUtils.isNotBlank(sortOrder[0])){
			statusSql.append("order by a." + sortField[0] + " " + sortOrder[0]); 
		} else {
			statusSql.append("order by a.createTime desc ");
		}
		
		Page page = this.iBaseDao.getPage(ParamUtil.getInteger(map,"pageIndex",1),ParamUtil.getInteger(map, "pageSize", 20),
				map, countSql.toString(), statusSql.toString(), objectList);
		List<MedicalOrders> list = new ArrayList<MedicalOrders>();
		if(SystemConfig.ORDERS_LIST_UNALLOCATE.equals(orders.getListType())) {
			for(Object obj : page.getResult()) {
				MedicalOrders bean = (MedicalOrders) obj;
				bean.setTotalMoney(bean.getPayment().add(bean.getFreight()));
				bean.setMediaId(bean.getMedia().getId());
				list.add(bean);
			}
		} else {
			for(Object obj : page.getResult()) {
				MedicalOrders bean = (MedicalOrders) obj;
				MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, bean.getCheckUserId());
				bean.setCheckUserName(checkUser.getName());
				bean.setTotalMoney(bean.getPayment().add(bean.getFreight()));
				list.add(bean);
			}
		}
		page.setResult(list);
		return page;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void groupRecover(String ordersIds) {
		String ordersId[] = ordersIds.split(",");
		for(String oId : ordersId) {
			MedicalOrders orders = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, oId);
			orders.setCheckUserId("");
			orders.setAllocateGrade(SystemConfig.ORDERS_GRADE_GROUP);
		}
	}
	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void allocateCenter(String ordersIds, String centerIds) {
		String ordersId[] = ordersIds.split(",");
		String centerId[] = centerIds.split(",");
		List<String> ordersIdList = new ArrayList<String>(Arrays.asList(ordersId));
		List<String> centerIdList = new ArrayList<String>(Arrays.asList(centerId));
		for(int i=0; i<ordersId.length; i++){
			MedicalOrders orders = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, ordersIdList.get(i));
			orders.setCenterId(centerIdList.get(i % centerIdList.size()));
			orders.setAllocateGrade(SystemConfig.ORDERS_GRADE_CENTER);
			orders.setAlloateTime(new Date());
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void allocateGroup(String ordersIds, String groupIds) {
		String ordersId[] = ordersIds.split(",");
		String groupId[] = groupIds.split(",");
		List<String> ordersIdList = new ArrayList<String>(Arrays.asList(ordersId));
		List<String> groupIdList = new ArrayList<String>(Arrays.asList(groupId));
		for(int i=0; i<ordersId.length; i++){
			MedicalOrders orders = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, ordersIdList.get(i));
			MedicalGroup group = (MedicalGroup) this.iBaseDao.getObject(MedicalGroup.class, groupIdList.get(i % groupIdList.size()));
			orders.setCenterId(group.getPlatform().getId());
			orders.setGroupId(group.getId());
			orders.setAllocateGrade(SystemConfig.ORDERS_GRADE_GROUP);
			orders.setAlloateTime(new Date());
		}
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void allocateUser(String ordersIds, String userIds) {
		String ordersId[] = ordersIds.split(",");
		String userId[] = userIds.split(",");
		List<String> ordersIdList = new ArrayList<String>(Arrays.asList(ordersId));
		List<String> userIdList = new ArrayList<String>(Arrays.asList(userId));
		for(int i=0; i<ordersId.length; i++){
			MedicalOrders orders = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, ordersIdList.get(i));
			MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, userIdList.get(i % userIdList.size()));
			if(!admin.getIsSuper().equals(SystemConfig.SUPER_ADMIN)) {
				orders.setCenterId(admin.getGroup().getPlatform().getId());
				orders.setGroupId(admin.getGroup().getId());
			}
			orders.setCheckUserId(admin.getId());
			orders.setAllocateGrade(SystemConfig.ORDERS_GRADE_USER);
			orders.setAlloateTime(new Date());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalPlatform> findUserCenterList(String hospitalId) {
		return this.iBaseDao.getBySql("from MedicalPlatform a where a.eid=? and a.platformType=? ", null, hospitalId, SystemConfig.ORDERS_CENTER_TYPE);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalGroup> findUserGroupList(String centerId) {
		return this.iBaseDao.getBySql("from MedicalGroup a where a.platform.id=? ", null, centerId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalAdmin> findUserList(String groupId) {
		return this.iBaseDao.getBySql("from MedicalAdmin a where a.group.id=? and a.onlineStatus=? ", null, groupId, SystemConfig.ONLINE_STATUS);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalGroup> findCurCenGroupList(MedicalAdmin admin) {
		if(SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			return this.iBaseDao.getBySql("from MedicalGroup a where a.eid=? and a.platform.platformType=? ", null, admin.getEnterpriseId(), SystemConfig.ORDERS_CENTER_TYPE);
		} else {
			return this.iBaseDao.getBySql("from MedicalGroup a where a.platform.id=? ", null, admin.getGroup().getPlatform().getId());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalAdmin> findCurGroUserList(MedicalAdmin admin) {
		return this.iBaseDao.getBySql("from MedicalAdmin a where a.group.id=? ", null, admin.getGroup().getId());
	}

	@Override
	public Workbook exportOrdersCurrent(String ids) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_ALLOCATION);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalOrders order = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, ordersIds[j]);
				i++;
				Row currentRow = sheet.createRow(i);
				currentRow.createCell(0).setCellValue(i);
				if(null != order){
					currentRow.createCell(1).setCellValue(order.getSerialNum());
					currentRow.createCell(2).setCellValue(order.getCreateTime());
					currentRow.createCell(3).setCellValue(order.getName());
					currentRow.createCell(4).setCellValue(order.getAddress());
					BigDecimal total = new BigDecimal(0);
					if(null != order.getPayment()) {
						currentRow.createCell(5).setCellValue(order.getPayment().toString());
						total = total.add(order.getPayment());
					}
					if(null != order.getFreight()) {
						currentRow.createCell(6).setCellValue(order.getFreight().toString());
						total = total.add(order.getFreight());
					}
					currentRow.createCell(7).setCellValue(total.toString());
				}
			}
		}
		return workbook;
	}

	@SuppressWarnings("all")
	@Override
	public Workbook exportOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_ALLOCATION);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? and m.status=? and m.allocateGrade = ? ");
		objectList.add(admin.getEnterpriseId());
		objectList.add(SystemConfig.ORDERS_WAIT_AUDIT_TYPE);
		objectList.add(SystemConfig.ORDERS_GRADE_INIT);
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			hql.append("and m.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		if(StringUtils.isNotBlank(orders.getName())) {
			hql.append("and m.name like ? ");
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			objectList.add("%"+name+"%");
		}
		List<MedicalOrders> ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCreateTime());
				currentRow.createCell(3).setCellValue(order.getName());
				currentRow.createCell(4).setCellValue(order.getAddress());
				BigDecimal total = new BigDecimal(0);
				if(null != order.getPayment()) {
					currentRow.createCell(5).setCellValue(order.getPayment().toString());
					total = total.add(order.getPayment());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(6).setCellValue(order.getFreight().toString());
					total = total.add(order.getFreight());
				}
				currentRow.createCell(7).setCellValue(total.toString());
			}
		}
		return workbook;
	}
	
	@SuppressWarnings("all")
	@Override
	public Workbook exportCenterOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_ALLOCATION);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? and m.allocateGrade = ? ");
		objectList.add(admin.getEnterpriseId());
		objectList.add(SystemConfig.ORDERS_GRADE_CENTER);
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			hql.append("and m.centerId=? ");
			objectList.add(admin.getGroup().getPlatform().getId());
		}
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			hql.append("and m.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		if(StringUtils.isNotBlank(orders.getName())) {
			hql.append("and m.name like ? ");
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			objectList.add("%"+name+"%");
		}
		List<MedicalOrders> ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCreateTime());
				currentRow.createCell(3).setCellValue(order.getName());
				currentRow.createCell(4).setCellValue(order.getAddress());
				BigDecimal total = new BigDecimal(0);
				if(null != order.getPayment()) {
					currentRow.createCell(5).setCellValue(order.getPayment().toString());
					total = total.add(order.getPayment());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(6).setCellValue(order.getFreight().toString());
					total = total.add(order.getFreight());
				}
				currentRow.createCell(7).setCellValue(total.toString());
			}
		}
		return workbook;
	}

	
	@SuppressWarnings("all")
	@Override
	public Workbook exportGroupOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_ALLOCATION);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? and m.allocateGrade = ? ");
		objectList.add(admin.getEnterpriseId());
		objectList.add(SystemConfig.ORDERS_GRADE_GROUP);
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			hql.append("and m.groupId=? ");
			objectList.add(admin.getGroup().getId());
		}
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			hql.append("and m.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		if(StringUtils.isNotBlank(orders.getName())) {
			hql.append("and m.name like ? ");
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			objectList.add("%"+name+"%");
		}
		List<MedicalOrders> ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCreateTime());
				currentRow.createCell(3).setCellValue(order.getName());
				currentRow.createCell(4).setCellValue(order.getAddress());
				BigDecimal total = new BigDecimal(0);
				if(null != order.getPayment()) {
					currentRow.createCell(5).setCellValue(order.getPayment().toString());
					total = total.add(order.getPayment());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(6).setCellValue(order.getFreight().toString());
					total = total.add(order.getFreight());
				}
				currentRow.createCell(7).setCellValue(total.toString());
			}
		}
		return workbook;
	}
	
	
	
	@Override
	public Workbook exportAllocatedOrdersCurrent(String ids) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_ALLOCATED);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}	
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		if(StringUtils.isNotBlank(ids)){
			String [] ordersIds =  ids.split(",");
			for(int j=0;j<ordersIds.length;j++){
				// 获得记录
				MedicalOrders order = (MedicalOrders) this.iBaseDao.getObject(MedicalOrders.class, ordersIds[j]);
				i++;
				Row currentRow = sheet.createRow(i);
				currentRow.createCell(0).setCellValue(i);
				if(null != order){
					currentRow.createCell(1).setCellValue(order.getSerialNum());
					currentRow.createCell(2).setCellValue(order.getCreateTime());
					currentRow.createCell(3).setCellValue(order.getName());
					currentRow.createCell(4).setCellValue(order.getAddress());
					BigDecimal total = new BigDecimal(0);
					if(null != order.getPayment()) {
						currentRow.createCell(5).setCellValue(order.getPayment().toString());
						total = total.add(order.getPayment());
					}
					if(null != order.getFreight()) {
						currentRow.createCell(6).setCellValue(order.getFreight().toString());
						total = total.add(order.getFreight());
					}
					currentRow.createCell(7).setCellValue(total.toString());
					if(StringUtils.isNotBlank(order.getCheckUserId())) {
					MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, order.getCheckUserId());
					if(null != checkUser && !SystemConfig.SUPER_ADMIN.equals(checkUser.getIsSuper())) {
						currentRow.createCell(8).setCellValue(checkUser.getGroup().getPlatform().getName());
						currentRow.createCell(9).setCellValue(checkUser.getGroup().getName());
						currentRow.createCell(10).setCellValue(checkUser.getName());
					}
				}
				}
			}
		}
		return workbook;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportAllocatedOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_ALLOCATED);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? and m.status=? and m.allocateGrade <> ? ");
		objectList.add(admin.getEnterpriseId());
		objectList.add(SystemConfig.ORDERS_WAIT_AUDIT_TYPE);
		objectList.add(SystemConfig.ORDERS_GRADE_INIT);
		
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			hql.append("and m.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		if(StringUtils.isNotBlank(orders.getName())) {
			hql.append("and m.name like ? ");
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			objectList.add("%"+name+"%");
		}
		List<MedicalOrders> ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCreateTime());
				currentRow.createCell(3).setCellValue(order.getName());
				currentRow.createCell(4).setCellValue(order.getAddress());
				BigDecimal total = new BigDecimal(0);
				if(null != order.getPayment()) {
					currentRow.createCell(5).setCellValue(order.getPayment().toString());
					total = total.add(order.getPayment());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(6).setCellValue(order.getFreight().toString());
					total = total.add(order.getFreight());
				}
				currentRow.createCell(7).setCellValue(total.toString());
				if(StringUtils.isNotBlank(order.getCheckUserId())) {
					MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, order.getCheckUserId());
					if(null != checkUser && !SystemConfig.SUPER_ADMIN.equals(checkUser.getIsSuper())) {
						currentRow.createCell(8).setCellValue(checkUser.getGroup().getPlatform().getName());
						currentRow.createCell(9).setCellValue(checkUser.getGroup().getName());
						currentRow.createCell(10).setCellValue(checkUser.getName());
					}
				}
			}
		}
		return workbook;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportAllocatedCenterOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_ALLOCATED);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? and m.allocateGrade in (?,?) ");
		objectList.add(admin.getEnterpriseId());
		objectList.add(SystemConfig.ORDERS_GRADE_GROUP);
		objectList.add(SystemConfig.ORDERS_GRADE_USER);
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			hql.append("and m.centerId=? ");
			objectList.add(admin.getGroup().getPlatform().getId());
		}
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			hql.append("and m.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		if(StringUtils.isNotBlank(orders.getName())) {
			hql.append("and m.name like ? ");
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			objectList.add("%"+name+"%");
		}
		List<MedicalOrders> ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCreateTime());
				currentRow.createCell(3).setCellValue(order.getName());
				currentRow.createCell(4).setCellValue(order.getAddress());
				BigDecimal total = new BigDecimal(0);
				if(null != order.getPayment()) {
					currentRow.createCell(5).setCellValue(order.getPayment().toString());
					total = total.add(order.getPayment());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(6).setCellValue(order.getFreight().toString());
					total = total.add(order.getFreight());
				}
				currentRow.createCell(7).setCellValue(total.toString());
				if(StringUtils.isNotBlank(order.getCheckUserId())) {
					MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, order.getCheckUserId());
					if(null != checkUser && !SystemConfig.SUPER_ADMIN.equals(checkUser.getIsSuper())) {
						currentRow.createCell(8).setCellValue(checkUser.getGroup().getPlatform().getName());
						currentRow.createCell(9).setCellValue(checkUser.getGroup().getName());
						currentRow.createCell(10).setCellValue(checkUser.getName());
					}
				}
			}
		}
		return workbook;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Workbook exportAllocatedGroupOrdersAll(MedicalOrders orders, MedicalAdmin admin) throws Exception {
		String AbsolutelyPath = ServletActionContext.getServletContext().getRealPath(SystemConfig.EXPORT_ALLOCATED);
		File file = new File(AbsolutelyPath);
		if(!file.exists()){
			throw new FileNotFoundException("没有找到excel文件");
		}
		InputStream is = new FileInputStream(file);
		Workbook workbook = WorkbookFactory.create(is);
		is.close();

		Sheet sheet = workbook.getSheetAt(0);
		int i=0;
		
		List<Object> objectList = new ArrayList<Object>();
		StringBuilder hql = new StringBuilder("from MedicalOrders m where 1=1 and m.hospitalId = ? and m.allocateGrade = ? ");
		objectList.add(admin.getEnterpriseId());
		objectList.add(SystemConfig.ORDERS_GRADE_USER);
		if(!SystemConfig.SUPER_ADMIN.equals(admin.getIsSuper())) {
			hql.append("and m.groupId=? ");
			objectList.add(admin.getGroup().getId());
		}
		if(StringUtils.isNotBlank(orders.getSerialNum())) {
			hql.append("and m.serialNum=? ");
			objectList.add(orders.getSerialNum());
		}
		if(StringUtils.isNotBlank(orders.getName())) {
			hql.append("and m.name like ? ");
			String name = orders.getName().trim().replaceAll("_", "chr(95)").replaceAll("%", "chr(37)");
			objectList.add("%"+name+"%");
		}
		List<MedicalOrders> ordersList = this.iBaseDao.getBySql(hql.toString(), null, objectList.toArray());
		
		// 遍历
		for (MedicalOrders order : ordersList) {
			Row currentRow = sheet.createRow(++i);
			currentRow.createCell(0).setCellValue(i);
			if(null != order){
				currentRow.createCell(1).setCellValue(order.getSerialNum());
				currentRow.createCell(2).setCellValue(order.getCreateTime());
				currentRow.createCell(3).setCellValue(order.getName());
				currentRow.createCell(4).setCellValue(order.getAddress());
				BigDecimal total = new BigDecimal(0);
				if(null != order.getPayment()) {
					currentRow.createCell(5).setCellValue(order.getPayment().toString());
					total = total.add(order.getPayment());
				}
				if(null != order.getFreight()) {
					currentRow.createCell(6).setCellValue(order.getFreight().toString());
					total = total.add(order.getFreight());
				}
				currentRow.createCell(7).setCellValue(total.toString());
				if(StringUtils.isNotBlank(order.getCheckUserId())) {
					MedicalAdmin checkUser = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, order.getCheckUserId());
					if(null != checkUser && !SystemConfig.SUPER_ADMIN.equals(checkUser.getIsSuper())) {
						currentRow.createCell(8).setCellValue(checkUser.getGroup().getPlatform().getName());
						currentRow.createCell(9).setCellValue(checkUser.getGroup().getName());
						currentRow.createCell(10).setCellValue(checkUser.getName());
					}
				}
			}
		}
		return workbook;
	}
	
}
